package com.hnjowe.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import org.apache.log4j.Logger;

/**
 * 页面静态化：从动态页的URL获取相应页面内容并写入到文件
 * filename: MakeHtml.java
 * project:  CCTR
 * @company Hainan Jowe Technology Ltd
 * @author wangxiuwu
 * @create in 2009-12-15
 * @version 1.0
 */
public class MakeHtml {
	private static Logger log = Logger.getLogger(MakeHtml.class.getName());
	private static long star = 0;
	private static long end = 0;
	private static long ttime = 0;

	/*返回html代码*/
	public static String getHtmlCode(String httpUrl) {
		Date before = new Date();
		star = before.getTime();
		String htmlCode = "";
		try {
			InputStream in;
			URL url = new java.net.URL(httpUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("User-Agent", "Mozilla/4.0");
			connection.connect();
			in = connection.getInputStream();
			java.io.BufferedReader breader = new BufferedReader(new InputStreamReader(in, "utf-8"));
			
			
			String currentLine;
			while ((currentLine = breader.readLine()) != null) {
				// htmlCode+=currentLine;
				htmlCode = htmlCode + currentLine + "\n";
			}
		} catch (Exception e) {
			log.error(e);
		} finally {
			Date after = new Date();
			end = after.getTime();
			ttime = end - star;
			log.error("生成静态页面前访问[" + httpUrl + "]执行时间:" + ttime + "毫秒");
		}
		return htmlCode;
	}

	/*存储文件*/
	public static synchronized void writeHtml(String filePath, String info,String flag) {
		try {
			File writeFile = new File(filePath);
			boolean isExit = writeFile.exists();
			if (isExit != true) {// 文件不存在，创建文件
				writeFile.createNewFile();

			} else {// 文件已存在
				if (!flag.equals("NO")) {// 如果标记flag不等于NO，则删除文件，再重新创建
					writeFile.delete();
					writeFile.createNewFile();
				}
			}
			// 写入文件
			FileOutputStream writerStream = new FileOutputStream(filePath,true);
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(writerStream, "utf-8"));
			writer.write(info);   
			writer.close();
		} catch (Exception ex) {
			log.error(ex.getMessage());
		}
	}

	public static void main(String[] args) {
		String url = "http://www.easydone.cn/index.htm";
		writeHtml("c:/demo.htm", getHtmlCode(url), "NO");
	}
}
